package anonymouschat.client;

import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;

import anonymouschat.utils.Print;

/**
 * Contains all the information to be distributed to the servers, and other users that wish
 * to communicate with a particular user
 * <br/>
 * <br/>
 * Static Methods:<br/>
 *      composeUserName -- Used to see what user name is associated with two keys given
 */
public class PublicIdentity implements Serializable {
	private static final long serialVersionUID = 8577187468621789457L;
	private PublicKey publicRSAKey; // Key used to encrypt messages to the user
	private PublicKey verKey; //Key used to verify messages came from the user.
	private String userName; //User name = SHA-256_Hash(encKey || verKey)

	public PublicIdentity(Identity ident) {
		setPublicRSAKey(ident.getPublicRSAKey());
		setVerKey(ident.getVerKey());
		setUserName(ident.getUserName());
	}

	private void setPublicRSAKey(PublicKey myPublicRSAKey) {
		this.publicRSAKey = myPublicRSAKey;
	}

	public PublicKey getPublicRSAKey() {
		return publicRSAKey;
	}

	private void setVerKey(PublicKey myVerKey) {
		this.verKey = myVerKey;
	}

	public PublicKey getVerKey() {
		return verKey;
	}

	private void setUserName(String myName) {
		this.userName = myName;
	}

	public String getUserName() {
		return userName;
	}
	
	/**
	 * Generates the user's id string by composing the encKey and the verKey, then taking the hash
	 * of the result.
     * @return
     *      User's id string
     */
    public static String composeUserName(PublicKey encKey,PublicKey verKey) {
        // hash sha 256
        MessageDigest md;
        String userNameString = null;
        try {
            md = MessageDigest.getInstance("SHA-256");
        
            byte[] pubKey = encKey.getEncoded();
            byte[] vKey = verKey.getEncoded();
            byte[] userKey = new byte[pubKey.length + vKey.length];
    
            System.arraycopy(pubKey, 0, userKey, 0, pubKey.length);
            System.arraycopy(vKey, 0, userKey, pubKey.length, vKey.length);
        
            md.update(userKey);
            byte[] userID = md.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < userID.length; i++) {
                sb.append(Integer.toString(userID[i]));
            }
            userNameString = sb.toString();
            Print.debug( "UserId is " + userNameString );
        } catch( NoSuchAlgorithmException e ) {
            Print.error( "Failed to compose username",e );
        }
        
        return userNameString;
    }

}
